package com.fht.spring_boot_study.listener;
import java.io.File;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@WebListener
public class LogListener implements ServletContextListener {

    private final static Logger LOGGER = LoggerFactory.getLogger(LogListener.class);

    @Override
    public void contextInitialized(ServletContextEvent sce) {
        LOGGER.debug("==== Init log listener ====");
        File file = new File("/log");
        if (file == null || !file.exists() || !file.isDirectory()) {
            return;
        }

        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        String currentDate = dateTimeFormatter.format(LocalDate.now());

        File[] files = file.listFiles();
        for (File temp : files) {
            String fileName = temp.getName();
            if (!fileName.contains(currentDate)) {
                temp.delete();
            }
        }
    }

    @Override
    public void contextDestroyed(ServletContextEvent sce) {
        LOGGER.debug("==== Destroyed log listener ====");
    }


}